package com.moon.controller;

import com.github.pagehelper.PageInfo;
import com.moon.anno.ReCommit;
import com.moon.dto.ProductVo;
import com.moon.dto.TUser;
import com.moon.service.ProductService;
import com.moon.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RequestMapping("/product")
@RestController
public class ProductController {

    @Autowired
    ProductService productService;

    @ReCommit(timeout = 10000)
    @RequestMapping("/insert")
    public String insert(@RequestParam("productName") String productName, @RequestBody List<MultipartFile> fileList,
                         @RequestParam("productDetail") String productDetail, HttpServletRequest request) {
        String token = request.getHeader("token");
        TUser user = JwtUtils.getObject(token, TUser.class);

        return productService.insert(productName, fileList, productDetail, user);
    }

    @RequestMapping("/select")
    public PageInfo<ProductVo> select(@RequestParam("currentPage") Integer currentPage, @RequestParam("pageSize") Integer pageSize,
                                     @RequestParam("keyword") String keyword, @RequestParam("status") Integer status , HttpServletRequest request) {
        String token = request.getHeader("token");
        TUser user = JwtUtils.getObject(token, TUser.class);

        PageInfo productInfo;

        if (keyword==null || "".equals(keyword)) {
            //没有关键词就去数据库查全部
            productInfo = productService.selectAll(user.getId(), status, currentPage, pageSize);
        } else {
            //不然去查ES
            productInfo = productService.selectByEs(user.getId(), keyword, status, currentPage, pageSize);
        }

        return productInfo;
    }

    @RequestMapping("/delete")
    public String delete(@RequestParam("productId") long productId) {
        return productService.delete(productId);
    }

    @ReCommit(timeout = 10000)
    @RequestMapping("/update")
    public String update(@RequestParam("id") long id, @RequestParam("productName") String productName,
                         @RequestBody List<MultipartFile> fileList, @RequestParam("productDetail") String productDetail) {
        return productService.update(id, productName, fileList, productDetail);
    }

}
